WebSocketManager = BaseClass:Extend()
local C_WebSocketManager = CS.WebSocketManager

function WebSocketManager:New()
    local o = NetManager.super.New(self)
    o.proto_callback = {}
    o:Init()
    return o
end

function WebSocketManager:Init()
    self:BindCallback()
end

function WebSocketManager:GetInstance()
    if self.instance == nil then
        self.instance = self:New()
    end
    return self.instance
end

function WebSocketManager:BindCallback()
    C_WebSocketManager.Instance:BindCallBack(
        function()
            Debug.Log("LUA: CONNECT_SUCCESS -----  连接成功")
            WebSocketManager.connect = true
            EventManager:Fire(Events.CONNECT_SUCCESS)
        end,
        function(data)
            self:HandlerReceiveData(data)
        end,
        function()
            WebSocketManager.connect = false
            -- Debug.Log("LUA: DISCONNECT -----  断开服务器连接")
            -- Message:Show("DISCONNECT")
        end
    )
end

--连接服务器
function WebSocketManager:Connect(ip)
    C_WebSocketManager.Instance:CreateWebSocket(ip)
end

--收到协议
function WebSocketManager:HandlerReceiveData(bytes)
    local cmd = CS.Utils.GetCmd(bytes)
    local _data = CS.Utils.GetData(bytes)
    local data = L_ProtoBuf:decode("sc", 2, cmd, _data)
    Debug.LogDump(data)

    if cmd and self.proto_callback[cmd] then
        Debug.Log("LUA: RECEIVE CMD : {0}", cmd)
        local pvo = self.proto_callback[cmd]
        if not pvo or not pvo.func then
            Debug.LogError("协议ID未绑定 {0}", cmd)
        else
            pvo.func(pvo.that, data)
        end
    end
end

--发送协议
function WebSocketManager:Request(msg, data)
    local bytes, msgId = L_ProtoBuf:encode("cs", msg, data)
    -- Debug.Log("bytes={0},msgId={1}", bytes, msgId)
    C_WebSocketManager.Instance:Send(msgId, bytes)
end

--绑定协议
function WebSocketManager:BindProto(id, func, that)
    if not self.proto_callback then self.proto_callback = {} end
    self.proto_callback[id] = { that = that, func = func }
end

--解绑协议
function WebSocketManager:UnBindProto(id)
    if self.proto_callback[id] then self.proto_callback[id] = nil end
end